package com.jmb.api.core.http;

import com.jmb.api.common.constant.ProxyConstant;
import com.jmb.api.dto.system.HttpSettingDTO;
import com.jmb.api.service.HttpSettingService;
import com.jmb.api.to.system.HttpSettingTO;
import com.jmb.api.vo.system.HttpSettingVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Slf4j
@Component
public class RequestFactory {
    @Autowired
    private HttpSettingService httpSettingService;

    // 基于HttpsURLConnection创建，配置SSL信任所有证书，设置代理和超时参数
    public SimpleClientHttpRequestFactory URLConnection(){
        SimpleClientHttpRequestFactory factory =new SimpleClientHttpRequestFactory(){
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                try {
                    // 执行父类的初始化
                    super.prepareConnection(connection, httpMethod);
                    // 处理HTTPS连接
                    if (connection instanceof HttpsURLConnection){
                        // 此信任策略将接受所有证书，存在安全风险！
                        TrustStrategy acceptAllTrustStrategy = (chain, authType) -> true;
                        SSLContext sslContext = SSLContexts.custom()
                                .loadTrustMaterial(null,acceptAllTrustStrategy).build();
                        ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
                        // 禁用主机名验证
                    }
                } catch (Exception e){
                    log.error("创建请求HttpsURLConnection失败",e);
                    throw new IOException("创建请求HttpsURLConnection失败",e);
                }
            }
        };
        Proxy proxy = proxyURLConnection();
        if (proxy!=null){
            factory.setProxy(proxy);
        }
        factory.setReadTimeout(readTimeout());
        factory.setConnectTimeout(connectTimeout());
        return factory;
    }
    // 设置URLConnection代理和超时参数
    private Proxy proxyURLConnection(){
        HttpSettingDTO proxy = null;
        List<HttpSettingDTO> httpSettingList = httpSettingService.getHttpSettingList(createProxySettingTO());
        if (!httpSettingList.isEmpty()){
            proxy = httpSettingList.get(0);
        }
        if (proxy!=null){
            String[] domain = proxy.getValue().split(":");
            String host = domain[0];
            int port = Integer.parseInt(domain[1]);
            return new Proxy(Proxy.Type.HTTP,new InetSocketAddress(host,port));
        }
        return null;
    }

    //  支持http https 底层基于HttpClient
    public HttpComponentsClientHttpRequestFactory HttpClient()  {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        try {
            SSLContexts.custom().loadTrustMaterial(null, (x509Certificates, s) -> true).build();
        } catch (Exception e){
            log.error("创建请求HttpClient失败",e);
        }
        HttpClientBuilder custom = HttpClients.custom();
        try {
            custom.setProxy(proxyHttpClient());
        } catch (URISyntaxException e) {
            log.error("创建请求HttpClient失败",e);
        }
        CloseableHttpClient client = custom.build();
        factory.setHttpClient(client);
        factory.setConnectionRequestTimeout(readTimeout());
        factory.setConnectTimeout(connectTimeout());
        return factory;
    }

    // 设置httpClient代理和超时参数
    private HttpHost proxyHttpClient() throws URISyntaxException {
        HttpSettingDTO proxy = null;
        List<HttpSettingDTO> httpSettingList = httpSettingService.getHttpSettingList(createProxySettingTO());
        if (!httpSettingList.isEmpty()){
            proxy = httpSettingList.get(0);
        }
        if (proxy!=null){
            return HttpHost.create(proxy.getValue());
        }
        return null;
    }

    //获取超时时间
    private Integer getTimeout(Integer type,Integer defaultValue){
        HttpSettingDTO dto = new HttpSettingDTO();
        dto.setStatusId(ProxyConstant.PROXY_STATUS);
        dto.setType(type);
        List<HttpSettingDTO> httpSettingList = httpSettingService.getHttpSettingList(dto);
        if (httpSettingList.isEmpty()){
            return defaultValue;
        }
        // 超时时间
        String value = httpSettingList.get(0).getValue();
        if (value == null || value.trim().isEmpty()){
            return defaultValue;
        }
        // 超时时间
        int timeout = Integer.parseInt(value.trim());
        try {
            if (timeout < 0) {
                return defaultValue;
            }return timeout;
        }catch (NumberFormatException e){
            // 记录日志
            return defaultValue;
        }
    }

    // 提取公共方法
    private HttpSettingDTO createProxySettingTO(){
        HttpSettingDTO httpSettingTO = new HttpSettingDTO();
        httpSettingTO.setStatusId(ProxyConstant.PROXY_STATUS);
        httpSettingTO.setType(ProxyConstant.PROXY_TYPE);
        return httpSettingTO;
    }
    // 获取代理超时时间
    private Integer connectTimeout(){
        return getTimeout(ProxyConstant.TYPE_CONNECT_TIMEOUT, ProxyConstant.DEFAULT_CONNECT_TIMEOUT);
    }
    private Integer readTimeout(){
        return getTimeout(ProxyConstant.TYPE_READ_TIMEOUT, ProxyConstant.DEFAULT_READ_TIMEOUT);
    }



}
